var router = require("express").Router();
var multer = require("multer");
var fs = require("fs");
var upload = multer({dest:"upload"});
var middle = upload.array("mfiles");
var AlbumMap = require("./db/AlbumDB");

//删除指定元素
Array.prototype.removeByValue = function(val) {
  for(var i=0; i<this.length; i++) {
    if(this[i] == val) {
      this.splice(i, 1);
      break;
    }
  }
}

//刷新
router.get("/", async function (req, res) {
  // await AlbumMap.remove();
  let albumMap = await AlbumMap.findOne({name:"全部"},  { arr: {$slice: [0,2]}});
  let albumNames = await AlbumMap.find().where("name").ne("全部").select("name");
  if (!albumMap || albumMap.length == 0) {
    albumMap = new AlbumMap({name:"全部"});
    await albumMap.save();
  }
  let totalNum = (await AlbumMap.findOne({name:"全部"})).arr.length;
  res.send({albumNames,albumMap, totalNum});
})

//创建相册
router.post("/createalbum", async function (req, res) {
  const {name} = req.body;
  if ((await AlbumMap.find({name})).length != 0) {
  res.send({error:"相册名已存在！"});
  }else {
    let albumMap = new AlbumMap({name});
    albumMap.save();
    res.send();
  }
})

//点击相册
router.get("/albumgetitem", async function (req, res) {
  const {name} = req.query;
  let totalNum = (await AlbumMap.findOne({name})).arr.length;
  let albumMap = await AlbumMap.findOne({name}, { arr: {$slice: [0,2]}});//[n,m]从第n个开始 取出m个
  res.send({albumMap, totalNum});
})

//点击相册
router.get("/selectpage", async function (req, res) {
  const {page, name} = req.query;
  console.log(req.query);
  let index = (Number(page)-1)*2;
  let totalNum = (await AlbumMap.findOne({name})).arr.length;
  let albumMap = await AlbumMap.findOne({name}, { arr: {$slice: [index,2]}});//[n,m]从第n个开始 取出m个
  res.send({albumMap, totalNum});
})

//添加照片
router.post("/addphoto",middle,async function (req, res) {
  const {name} = req.body;
  await AlbumMap.update({name:"全部"},{$push:{"arr":{$each:req.files}}});//确保每次添加照片时 都会向全部相册里添加
  if (name !== "全部") {
    await AlbumMap.update({name},{$push:{"arr":{$each:req.files}}});
  }
  let totalNum = (await AlbumMap.findOne({name})).arr.length;
  let pages = Math.ceil(Number(totalNum)/2);
  let count = Number(totalNum)%2 == 0 ? 2 : 1;
  let albumMap = await AlbumMap.findOne({name}, {arr:{$slice:-count}});
  res.send({albumMap, totalNum});
})


//删除照片
router.post("/deletephoto",async function (req, res) {
  const {name, filename} = req.body;
   await AlbumMap.update({name},{$pull:{"arr":{filename}}});//// TODO:
  res.send();
})


//删除相册
router.post("/deletealbum",async function (req, res) {
  const {name} = req.body;
  await AlbumMap.remove({name});
  res.send();
})


//将图片 返回
router.get("/img/:imgname", function(req, res) {
  //图文数据的 读取流
  let fr = fs.createReadStream("upload/" +   req.params.imgname);
  //用管道 讲读取流 连接到 响应流
  fr.pipe(res);
});


module.exports = router;
